/**
 * 透明材质修复工具
 * 用于修复Three.js场景中透明材质导致的遮挡问题
 */

import * as THREE from 'three';

export class TransparentMaterialFixer {
    /**
     * 修复场景中所有透明材质
     * @param {THREE.Scene} scene - Three.js场景对象
     * @returns {Object} 修复统计信息
     */
    static fixAllTransparentMaterials(scene) {
        console.log('🔧 开始修复透明材质...');
        
        let transparentCount = 0;
        let opaqueCount = 0;
        
        scene.traverse((obj) => {
            if (obj.isMesh && obj.material) {
                const materials = Array.isArray(obj.material) ? obj.material : [obj.material];
                
                let hasTransparent = false;
                
                materials.forEach((mat) => {
                    // 检测是否是透明材质
                    const isTransparent = mat.transparent || 
                                         mat.alphaMap || 
                                         mat.alphaTest > 0 || 
                                         mat.opacity < 1.0 ||
                                         mat.userData.needsRenderOrder;
                    
                    if (isTransparent) {
                        // 🔑 根据物体类型使用不同的透明策略
                        const meshName = (obj.name || '').toLowerCase();
                        const isRoadLine = meshName.includes('road') || meshName.includes('line') || meshName.includes('马路') || meshName.includes('线');
                        
                        if (isRoadLine) {
                            // 🛣️ 马路线：使用alphaTest模式，保持深度写入
                            mat.transparent = false;  // 不使用透明混合
                            mat.alphaTest = mat.alphaTest || 0.5;  // 使用alpha测试
                            mat.depthWrite = true;    // 保持深度写入
                            mat.depthTest = true;
                            console.log(`   🛣️ 马路线使用alphaTest模式: ${obj.name}`);
                        } else {
                            // 🌿 其他透明物体：使用标准透明模式
                            mat.transparent = true;
                            mat.depthWrite = false; // 禁用深度写入，避免遮挡后面的物体
                            mat.depthTest = true;   // 保持深度测试开启
                            
                            // 如果有 alphaMap 但没有 alphaTest，设置默认值
                            if (mat.alphaMap && mat.alphaTest === 0) {
                                mat.alphaTest = 0.5;
                            }
                        }
                        
                        mat.needsUpdate = true;
                        hasTransparent = true;
                        transparentCount++;
                    } else {
                        opaqueCount++;
                    }
                });
                
                // 🔑 为包含透明材质的mesh设置分层renderOrder
                if (hasTransparent) {
                    // 根据物体类型和位置设置不同的renderOrder
                    const meshName = (obj.name || '').toLowerCase();
                    
                    if (meshName.includes('road') || meshName.includes('line') || meshName.includes('马路') || meshName.includes('线')) {
                        // 马路线等贴地透明物体：使用较低的renderOrder，但仍然在不透明物体之后
                        obj.renderOrder = 100;
                        console.log(`   🛣️ 马路线透明材质设置 renderOrder=100: ${obj.name}`);
                    } else if (obj.position.y < 0.1) {
                        // 接近地面的透明物体
                        obj.renderOrder = 200;
                        console.log(`   🏠 地面透明材质设置 renderOrder=200: ${obj.name}`);
                    } else {
                        // 其他透明物体（如玻璃、树叶等）
                        obj.renderOrder = 999;
                        console.log(`   🌿 空中透明材质设置 renderOrder=999: ${obj.name}`);
                    }
                }
            }
        });
        
        const result = {
            transparent: transparentCount,
            opaque: opaqueCount,
            total: transparentCount + opaqueCount
        };
        
        console.log('✅ 透明材质修复完成：');
        console.log(`   - 透明材质数量: ${transparentCount}`);
        console.log(`   - 不透明材质数量: ${opaqueCount}`);
        console.log(`   - 总计: ${result.total}`);
        
        // 触发渲染更新
        if (window.manager && window.manager.render) {
            window.manager.render();
        }
        
        return result;
    }
    
    /**
     * 检查材质是否为透明材质
     * @param {THREE.Material} material - 材质对象
     * @returns {boolean} 是否为透明材质
     */
    static isTransparentMaterial(material) {
        return material.transparent || 
               material.alphaMap || 
               material.alphaTest > 0 || 
               material.opacity < 1.0 ||
               material.userData.needsRenderOrder;
    }
    
    /**
     * 诊断场景中的透明材质问题
     * @param {THREE.Scene} scene - Three.js场景对象
     */
    static diagnose(scene) {
        console.log('\n╔════════════════════════════════════════════════════════════╗');
        console.log('║          透明材质诊断报告                                  ║');
        console.log('╚════════════════════════════════════════════════════════════╝\n');
        
        let transparentMeshes = [];
        let problematicMeshes = [];
        
        scene.traverse((obj) => {
            if (obj.isMesh && obj.material) {
                const materials = Array.isArray(obj.material) ? obj.material : [obj.material];
                
                materials.forEach((mat, index) => {
                    const isTransparent = this.isTransparentMaterial(mat);
                    
                    if (isTransparent) {
                        const info = {
                            meshName: obj.name || '(unnamed)',
                            materialIndex: index,
                            transparent: mat.transparent,
                            depthWrite: mat.depthWrite,
                            depthTest: mat.depthTest,
                            alphaTest: mat.alphaTest,
                            hasAlphaMap: !!mat.alphaMap,
                            opacity: mat.opacity,
                            renderOrder: obj.renderOrder
                        };
                        
                        transparentMeshes.push(info);
                        
                        // 检查是否有问题
                        if (mat.depthWrite === true) {
                            problematicMeshes.push({
                                ...info,
                                issue: 'depthWrite应该设置为false'
                            });
                        }
                        if (obj.renderOrder === 0 || obj.renderOrder === undefined) {
                            problematicMeshes.push({
                                ...info,
                                issue: 'renderOrder未设置或为0，建议设置为999'
                            });
                        }
                    }
                });
            }
        });
        
        console.log(`━━━ 透明材质统计 ━━━`);
        console.log(`找到 ${transparentMeshes.length} 个透明材质\n`);
        
        if (problematicMeshes.length > 0) {
            console.log(`🔴 发现 ${problematicMeshes.length} 个问题：\n`);
            problematicMeshes.slice(0, 10).forEach((item, index) => {
                console.log(`${index + 1}. Mesh: ${item.meshName}`);
                console.log(`   问题: ${item.issue}`);
                console.log(`   当前设置: depthWrite=${item.depthWrite}, renderOrder=${item.renderOrder}`);
                console.log('');
            });
            
            if (problematicMeshes.length > 10) {
                console.log(`   ... 还有 ${problematicMeshes.length - 10} 个问题未显示\n`);
            }
            
            console.log('╔════════════════════════════════════════════════════════════╗');
            console.log('║  推荐操作:                                                 ║');
            console.log('║  transparentFixer.fix()  - 一键修复所有透明材质问题       ║');
            console.log('╚════════════════════════════════════════════════════════════╝\n');
        } else {
            console.log('✅ 未发现透明材质问题！\n');
        }
        
        return {
            total: transparentMeshes.length,
            problematic: problematicMeshes.length,
            details: transparentMeshes
        };
    }
}

// 创建便捷实例
const transparentFixer = {
    // 修复所有透明材质
    fix: () => {
        const scene = window.manager?.getCurrentScene()?.scene;
        if (!scene) {
            console.error('❌ 场景未加载');
            return;
        }
        return TransparentMaterialFixer.fixAllTransparentMaterials(scene);
    },
    
    // 诊断透明材质问题
    diagnose: () => {
        const scene = window.manager?.getCurrentScene()?.scene;
        if (!scene) {
            console.error('❌ 场景未加载');
            return;
        }
        return TransparentMaterialFixer.diagnose(scene);
    },
    
    // 检查单个材质
    check: (material) => {
        return TransparentMaterialFixer.isTransparentMaterial(material);
    }
};

// 暴露到全局
if (typeof window !== 'undefined') {
    window.transparentFixer = transparentFixer;
    
    console.log('');
    console.log('╔════════════════════════════════════════════════════════════╗');
    console.log('║     🎭 透明材质修复工具已加载！                           ║');
    console.log('╚════════════════════════════════════════════════════════════╝');
    console.log('');
    console.log('📋 可用命令:');
    console.log('');
    console.log('  transparentFixer.diagnose()  ← 🔍 诊断透明材质问题');
    console.log('  transparentFixer.fix()       ← ✨ 一键修复所有问题');
    console.log('  transparentFixer.check(mat)  ← 🔎 检查单个材质');
    console.log('');
}

export default TransparentMaterialFixer;



